#!/usr/bin/env ruby
require 'rubygems'
require 'rspec'
require 'rspec/core/formatters/progress_formatter'
require 'rspec/core/runner'

# Disable ruby verbosity
# We need control over output so that the parallel task can parse it correctly
$VERBOSE = nil

module Parallel
  module RSpec
    #
    # Responsible for formatting output.
    # This differs from the built-in progress formatter by not appending an index to failures.
    #
    class Formatter < ::RSpec::Core::Formatters::ProgressFormatter
      ::RSpec::Core::Formatters.register self, :dump_failure
      def dump_failure(example, _)
        # Unlike the super class implementation, do not print the failure number
        output.puts "#{short_padding}#{example.full_description}"
        dump_failure_info(example)
      end
    end
    #
    # Responsible for running spec files given a spec file.
    # Can supply an optional list of additional options (used when running in CI).
    # We do it this way so that we can run very long spec file lists on Windows, since
    # Windows has a limited argument length depending on method of invocation.
    #
    class Runner
      def initialize(specs_file, options = [])
        abort "error: spec list file '#{specs_file}' does not exist." unless File.exist? specs_file
        if options.empty?
          @options = ['-fParallel::RSpec::Formatter']
        else
          @options = options
        end
        File.readlines(specs_file).each { |line| @options << line.chomp }
      end

      def run
        @options = ::RSpec::Core::ConfigurationOptions.new(@options)
        ::RSpec::Core::Runner.new(@options).run($stderr, $stdout)
      end
    end
  end
end

def print_usage
  puts 'usage: rspec_runner <spec_list_file> [<rspec_options_string>]'
end

if __FILE__ == $0
  if ARGV.length < 1
    print_usage
  else
    if ARGV.length == 1
      exit Parallel::RSpec::Runner.new(ARGV[0]).run
    else
      spec_file, *options = ARGV
      exit Parallel::RSpec::Runner.new(spec_file, options).run
    end
  end
end
